#include "HtmlUtil.h"
#include <fstream>
#include <tuple>
#include <vector>


char* HtmlUtil::readFile(std::string& file_name){
    // std::string file_name = "/data/data/com.termux/files/home/wiki/cpp/eel.is/c++draft/tuple";
    // std::string file_name = "/data/data/com.termux/files/home/wiki/cpp/html-book-20220730/reference/en/cpp/utility/tuple.html";
    std::ifstream file(file_name);
    file.seekg(0, std::ios::end);
	int fileLength = file.tellg();

	file.seekg(0, std::ios::beg);

	char* buffer = new char[fileLength + 1];
	file.read(buffer, fileLength);
	buffer[fileLength] = '\0';
    return buffer;
}

std::vector<std::string> HtmlUtil::getCppSource(std::string& file_name){
  CDocument doc;
  doc.parse(HtmlUtil::readFile(file_name));
  // CSelection c = doc.find("h1,h2,h3,h4");  
  CSelection c = doc.find(".source-cpp pre.de1, .source-text pre.de1");
  int size = c.nodeNum();
  std::vector<std::string> ret ;
  for(int i = 0;i<size;i++){
      ret.push_back(c.nodeAt(i).text());
   // std::cout << c.nodeAt(i).text() << std::endl; // some link
  }
  return ret;
}
std::vector<std::string> HtmlUtil::getRustSource(std::string& file_name){
  CDocument doc;
  doc.parse(HtmlUtil::readFile(file_name));
  // CSelection c = doc.find("h1,h2,h3,h4");  
  CSelection c = doc.find(".example-wrap pre,pre code.language-rust,pre code.playground,pre code.language-console");
  int size = c.nodeNum();
  std::vector<std::string> ret ;
  for(int i = 0;i<size;i++){
      ret.push_back(c.nodeAt(i).text());
   // std::cout << c.nodeAt(i).text() << std::endl; // some link
  }
  return ret;
}


void HtmlUtil::getHeaders(std::string& file_name){
  CDocument doc;
  doc.parse(HtmlUtil::readFile(file_name));
  CSelection c = doc.find("h1,h2,h3,h4,h5,h6");  
  int size = c.nodeNum();
  for(int i = 0;i<size;i++){
    std::cout << c.nodeAt(i).text() << std::endl; // some link
  }
}

/**
 * 只针对psql文档中的代码
 * */
std::vector<std::tuple<std::string,std::string>> HtmlUtil::getPsqlCode(std::string& file_name){
  CDocument doc;
  doc.parse(HtmlUtil::readFile(file_name));
  CSelection c = doc.find("pre.programlisting");  
  int size = c.nodeNum();
  std::vector<std::tuple<std::string,std::string>> ret;
  std::string desc = "";
  for(int i = 0;i<size;i++){
      auto node = c.nodeAt(i);
      auto prev = node.prevSibling();
      if(prev.valid() && prev.tag() == "p"){
          desc = prev.text();
      }
      ret.push_back(std::make_tuple(desc,node.text()));
  }

  return ret;
}
